package com.loanapp.server.market.provider.modular.platform.service.impl;

import com.loanapp.base.common.utils.DoubleUtil;
import com.loanapp.base.common.utils.StringUtil;
import com.loanapp.base.database.common.base.SqlMapper;
import com.loanapp.server.market.api.customer.entity.CustomerPlatformVisitInfo;
import com.loanapp.server.market.provider.modular.customer.service.CustomerPlatformVisitInfoService;
import com.loanapp.server.market.provider.modular.platform.service.PlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yuzhengxing on 2017/8/23.
 */
@Service
public class PlatformServiceImpl implements PlatformService {

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    private CustomerPlatformVisitInfoService customerPlatformVisitInfoService;

    /**
     * 查询贷款页产品
     * @param pageNum
     * @param pageSize
     * @param sortInfoId
     * @return
     */
    @Override
    public List<Map<String, Object>> getPlatformList(int pageNum, int pageSize,int sortInfoId) {
        String sql = "SELECT b.product_name abbreviation,b.product_img logo,b.min_quato minQuato,b.max_quato maxQuato,b.id,b.min_cycle minCycle,b.max_cycle maxCycle,FORMAT(b.daily_interest_rate * 30,2) dailyInteresRate,b.fastest_audit_circle lendSpeed FROM platform_company_info  a LEFT JOIN platform_product_info b on a.id=b.company_id LEFT JOIN platform_product_sort c on b.id=c.product_id  where a.status =1  and a.ifdel!=1 and b.status=1 and b.ifdel!=1 and c.sort_type=" +
                + sortInfoId +
                " ORDER BY  c.sort_num  limit "
                + (pageNum - 1) * pageSize + "," + pageSize;

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> platFormList = sqlMapper.selectList(sql);
        if (!CollectionUtils.isEmpty(platFormList)) {
            for (Map<String, Object> map : platFormList) {
                Map<String, Object> platFormMap = new HashMap<String, Object>();
                platFormMap .put("sortName", StringUtil.toString(map.get("sortName")));// 排序类别
                platFormMap.put("platformId", StringUtil.toString(map.get("id")));// 平台ID
                platFormMap.put("abbreviation", StringUtil.toString(map.get("abbreviation")));// 产品名称
                platFormMap.put("logo", StringUtil.toString(map.get("logo")));// logo
                platFormMap.put("quato",
                        getQuato(StringUtil.toString(map.get("minQuato")), StringUtil.toString(map.get("maxQuato"))));// 放款额度
                platFormMap.put("label", getPlatformLabel(StringUtil.toString(map.get("id"))));// 标签
                platFormMap.put("dailyInterestRate", StringUtil.toString(map.get("dailyInteresRate")));// 月利率
                Integer minCycle=null;
                if(StringUtil.isNotEmpty(map.get("minCycle"))){
                    minCycle=(int)map.get("minCycle");
                }
                platFormMap.put("maxCycle",
                        getCycle(minCycle,(int)map.get("maxCycle")) + "天");// 期限范围
                platFormMap .put("lendSpeed", StringUtil.toString(map.get("lendSpeed")) + "小时");// 最快放款
               // platFormMap.put("isFirst", getIsFirstClick("1001779", StringUtil.toString(map.get("id"))));// 是否首次点击
                list.add(platFormMap);
            }
        }
        return list;
    }

    /**
     * 获取平台标签
     * @param platformId
     * @return
     */

    @Override
    public String getPlatformLabel(String platformId) {
        String labelSql = "select c.label_name labelName from platform_product_info a inner join platform_product_label_relation b on a.id=b.product_id left join platform_product_label c on b.label_id=c.id where a.id="
                + platformId;
        List<Map<String, Object>> lableList = sqlMapper.selectList(labelSql);
        String label = "";
        if (!CollectionUtils.isEmpty(lableList)) {
            for (int i = 0; i < lableList.size(); i++) {
                label += StringUtil.toString(lableList.get(i).get("labelName")) + ",";
            }
        }
        return StringUtil.removeEnd(label, ",");
    }

    /**
     * 查询产品详情
     * @param platformId
     * @return
     */
    @Override
    public Map<String, Object> getPlatformDetail(String platformId) {
        String sql = "select a.product_name abbreviation,a.daily_interest_rate,a.product_img logo,a.advantage,a.min_quato minQuato,a.max_quato maxQuato,a.max_cycle maxCycle,a.min_cycle minCycle,a.lend_speed lendSpeed,a.apply_condition applyCondition,a.require_document requireDocument,a.audit_process auditProcess,a.id,a.link,a.brief_introduction introduction from platform_product_info a  where a.id="
                + platformId + " limit 0,1";
        //log.info("【PlatFormServiceImpl.getPlatformDetail】sql:" + sql);
        Map<String, Object> map = sqlMapper.selectOne(sql);
        Map<String, Object> platMap = new HashMap<String, Object>();
        if (map != null) {
            platMap.put("abbreviation", StringUtil.toString(map.get("abbreviation")));// 产品名称
            platMap.put("logo", StringUtil.toString(map.get("logo")));// 产品图片
            platMap.put("advantage", StringUtil.toString(map.get("advantage")));// 产品优势
            platMap.put("statistics", getClickCount(platformId)+8848);// 申请人数，统计人数
            platMap.put("quato",
                    getQuato(StringUtil.toString(map.get("minQuato")), StringUtil.toString(map.get("maxQuato"))));// 放款额度

            Integer minCycle=null;
            if(StringUtil.isNotEmpty(map.get("minCycle"))){
                   minCycle=(int)map.get("minCycle");
            }
            platMap.put("maxCycle",
                    getCycle(minCycle,(int)map.get("maxCycle")) + "天");// 期限范围
            platMap.put("applyCondition", StringUtil.toString(map.get("applyCondition")));// 申请条件
            platMap.put("requireDocument", StringUtil.toString(map.get("requireDocument")));// 所需材料
            platMap.put("introduction", StringUtil.toString(map.get("introduction")));// 产品简介
            platMap.put("link", StringUtil.toString(map.get("link")));// 跳转链接
            platMap.put("dailyInterestRate", StringUtil.toString(map.get("daily_interest_rate")));// 日利率
            //platMap.put("isFirst", getIsFirstClick("1001779",platformId));// 是否首次点击
        }
        return platMap;
    }

    /**
     * 产品类别（1.明星产品，2.广告产品）
     * 取出广告产品id
     * @param productType
     * @return
     */
    @Override
    public Map<String, Object> getAdvertisingProduct(String productType) {
        String sql = "select a.id gId from platform_product_extra c LEFT JOIN platform_product_info a on a.id = c.product_id where c.product_type="
                + productType ;
        Map<String, Object> map = sqlMapper.selectOne(sql);
        return map;
    }

    /**
     * 查询贷款产品分类
     * @return
     */
    @Override
    public List<Map<String, Object>> getPlatformSortName(){
        String sortSql = "SELECT id sortInfoId,sort_name sortAllName from platform_product_sortInfo WHERE ifdel = 0";
        List<Map<String, Object>> sortList = sqlMapper.selectList(sortSql);
        return sortList;
    }

    /**
     * 查询首页的访问量
     * @return
     */
    public Integer getClickCount(){
        StringBuffer sql=new StringBuffer();
        sql.append("select sum(click_count) sum from customer_platform_count_info  " +
                "where 1=1 and update_time between CONCAT('" + "2016-01-01" + ", 00:00:00') and CONCAT('" + "2050-01-01"
                + ", 23:59:59')");
        Integer clickCount = sqlMapper.selectOne(sql.toString(),Integer.class);
        return clickCount;
    }

    /**
     * 放款额度
     * @param minQuato
     * @param maxQuato
     * @return
     */
    private String getQuato(String minQuato, String maxQuato) {
        String quato = "";
        if (!StringUtil.isEmpty(minQuato)) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato));
        }
        if (!StringUtil.isEmpty(maxQuato) &&!maxQuato.equals("0.00")) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
        }
        if (!StringUtil.isEmpty(minQuato) && !StringUtil.isEmpty(maxQuato)&&!maxQuato.equals("0.00")) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato)) + "~"
                    + DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
        }
        return quato;
    }

    /**
     * 求出期限范围
     * @param minCycle
     * @param maxCycle
     * @return
     */
    private String getCycle(Integer minCycle, Integer maxCycle) {
        String Cycle = "";
        if (minCycle!=null) {
            Cycle+= minCycle;
        }
        if (maxCycle!=null) {
            Cycle+=maxCycle;
        }
        if (minCycle!=null&&maxCycle!=null) {
            Cycle = minCycle + "~"
                    + maxCycle;
        }
        return Cycle;
    }

    /**
     * 查询申请人数
     * @param platformId
     * @return
     */
    private Integer getClickCount(String platformId) {
        String sql = "SELECT sum(click_count) from customer_platform_count_info where  platform_id ="+platformId;
        Integer count = sqlMapper.selectOne(sql,Integer.class);
        if (StringUtil.isEmpty(count)){
            return count = 0;
        }
        return  count;
    }
}
